package com.nit.store.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.nit.store.mapper.CartMapper;
import com.nit.store.mapper.ProductMapper;
import com.nit.store.pojo.dto.output.CartDto;
import com.nit.store.pojo.entity.Address;
import com.nit.store.pojo.entity.Cart;
import com.nit.store.pojo.entity.Product;
import com.nit.store.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author J1ay
 * @Date 2022/7/21 22:24
 * @Description
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CartMapper cartMapper;

    /**
     * 添加购物车
     * @param pid
     * @param amount
     * @param uid
     * @param username
     */
    @Override
    public void addToCart(long pid, long amount, long uid, String username) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        Product product = productMapper.selectById(pid);
        Cart cart = cartMapper.selectOne(wrapper.eq("pid", pid).last("limit 1"));
        if (cart == null) {
            cart = new Cart();
            cart.setPid(pid);
            cart.setCreatedUser(username);
            cart.setUid(uid);
            cart.setModifiedUser(username);
            cart.setNum(amount);
            cart.setPrice(amount * product.getPrice());
            cartMapper.insert(cart);
        } else {
            cart.setNum(amount+cart.getNum());
            cart.setPrice(cart.getNum() * product.getPrice());
            System.out.println(cart);
            cartMapper.updateById(cart);
        }

    }

    /**
     * 更新购物车商品数量
     * @param cid
     * @param num
     * @param uid
     */
    @Override
    public void updateCart(long cid, long num, long uid) {
        Cart cart = cartMapper.selectById(cid);
        if (0 == num) {
            delFromCart(cid);
        }
        else {
            cart.setNum(num);
            cartMapper.updateById(cart);
        }
    }


    /**
     * 从购物车中删除商品
     * @param cid
     */
    @Override
    public void delFromCart(long cid) {
        cartMapper.deleteById(cid);
    }

    /**
     * 根据uid查看购物车
     * @param uid
     * @return
     */
    @Override
    public CartDto[] getCartListByUid(long uid) {
        return cartMapper.getCartListByUid(uid);
    }

    /**
     * 根据cid查看购物车
     * @param cids
     * @return
     */
    @Override
    public CartDto[] getCartByCid(Long[] cids) {
        System.out.println(cids);
        return cartMapper.getCartByCid(cids);
    }
}
